package com.jin.webvideo.base.httpclient;

import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;

import java.io.Closeable;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

public abstract class HttpSurroundHandler {

    protected HttpHost host;
    protected List<Header> headers = new ArrayList<>(0);

    protected HttpSurroundHandler(HttpHost host) {
        this.host = host;
    }
    protected HttpSurroundHandler(URI uri) {
        this.host = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
    }

    /**
     * 请求前处理
     * @param request
     * @return
     */
    public HttpRequest handleRequest(HttpRequest request) {
        return request;
    }

    public HttpResponse handleResponse(HttpClient client, HttpRequest request, HttpResponse response) throws IOException {
        if (!chkLoggedIn(response)) {
            return response;
        }
        String json = loggedIn(response);
        // 未登录
        if (json == null) {
            EntityUtils.consume(response.getEntity());
            if (response instanceof Closeable closeable) {
                closeable.close();
            }
            // 登录操作
            if (login(client)){
                // 重新进行操作
                request = handleRequest(request);
                return client.execute(host, request);
            }
            throw new IOException("authentication failed");
        }
        response.setEntity(new StringEntity(json));
        return response;
    }

    protected HttpHost getHost() {
        return this.host;
    }
    /**
     * 是否进行登录检查
     * @param response
     * @return
     */
    protected boolean chkLoggedIn(HttpResponse response) {
        return true;
    }

    /**
     * 判断是否已登录
     * @param response
     * @return null未登录， 非null 数据
     * @throws IOException
     */
    protected String loggedIn(HttpResponse response) throws IOException {
        return EntityUtils.toString(response.getEntity());
    }

    /**
     * 登录处理
     */
    protected abstract boolean login(HttpClient client) throws IOException;
}
